package com.yt.server.example;

import java.util.List;
import com.yt.server.api.IServiceCapableConnection;
import com.yt.server.api.IConnection;
import com.yt.server.api.IGlobalScope;
import com.yt.server.api.IScope;
import com.yt.server.common.service.BaseServiceImpl;
import java.util.ArrayList;

/**
 * walk测试
 * 
 * @author Administrator
 * 
 */
public class WalkService extends BaseServiceImpl implements IWalkService {

	private IScope walkScope;

	public WalkService() {
		proxyName = "WalkProxy";
		facade.registerProxy(this);
	}

	@Override
	public void setDao(Object dao) {
		this.dao = dao;
	}

	@Override
	public void setRoot(IScope root) {
		this.root = root;
	}

	@Override
	public IScope getScope() {
		return walkScope;
	}

	@Override
	public void init() {
		IGlobalScope globalScope = (IGlobalScope) root;
		// IScope root = globalScope.getCommonRoot();
		globalScope.createChildScope(proxyName, SCOPE_TYPE, null, true);
		walkScope = globalScope.getScope(proxyName);
		System.out.println("WalkService inited.");
	}

	@Override
	public void synXY(IConnection conn, People people) {
		System.out.println(people + "  " + people.getId());
		people.setAction(0);
		for (IConnection connection : walkScope.getConnections()) {
			if (connection instanceof IServiceCapableConnection) {
				try {
					if (conn != connection)
						((IServiceCapableConnection) connection).notify(people);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		conn.setAttribute("people", people);
	}

	public void addPlay(IConnection conn, People people) {
		System.out.println(people + "  " + people.getId());
		try {
			conn.setAttribute("people", people);
			List<People> list = new ArrayList<People>();
			for (IConnection connection : walkScope.getConnections()) {
				if (connection instanceof IServiceCapableConnection) {
					try {
						if (conn != connection) {
							list.add((People) connection.getAttribute("people"));
							((IServiceCapableConnection) connection)
									.notify(people);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			((IServiceCapableConnection) conn).notify(list.toArray());
			walkScope.join(conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}